package com.spring.cloud.eurekaclientzuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import com.spring.cloud.commonutils.vo.UserInfo;
import com.spring.cloud.commonutils.vo.ResultMessage;


@Component
public class ValidateCodeFilter extends ZuulFilter {

    private final static String VALIDATE_KEY_PARAM_NAME = "validateKey";
    private final static String VALIDATE_CODE_PARAM_NAME = "validateCode";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override //过滤器位置的类型
    public String filterType() {
        //类型 pre route post error
        return FilterConstants.PRE_TYPE;
    }

    @Override //过滤器排序
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 15;
    }

    @Override
    public boolean shouldFilter() {

        //获取请求上下文 用于过去参数
        RequestContext ctx = RequestContext.getCurrentContext();

        //判断参数是否存在
        if(ctx.getRequestQueryParams() == null){
            return false;
        }

        //判断参数是否相等
        return ctx.getRequestQueryParams().containsKey(VALIDATE_CODE_PARAM_NAME) &&
                ctx.getRequestQueryParams().containsKey(VALIDATE_KEY_PARAM_NAME);
    }

    @Override   //过滤器核心逻辑
    public Object run() throws ZuulException {

        //获取请求上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取参数
        String validateKey = ctx.getRequest().getParameter(VALIDATE_KEY_PARAM_NAME);
        String ValidateCode = ctx.getRequest().getParameter(VALIDATE_CODE_PARAM_NAME);

        //从redis中获取参数
        String redisValidateCode = stringRedisTemplate.opsForValue().get(validateKey);

        //判断参数是否相等
        if(ValidateCode.equals(redisValidateCode)){
            //null 为放行
            return null;
        }

        //不再放行路由,逻辑到此为止
        ctx.setSendZuulResponse(false);
        //设置响应码为401-未签名
        ctx.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        //设置响应类型
        ctx.getResponse().setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        //定义结果错误对象
        ResultMessage result = new ResultMessage(false,"验证码错误,请检查您的输入");
        ObjectMapper mapper = new ObjectMapper();
        String body = null;

        try {
            body = mapper.writeValueAsString(result);   //转换成JSON
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //设置响应体
        ctx.setResponseBody(body);
        return null;
    }
}
